$(function () {
    //检查token
    if (token == null || token == '') {
        vm.$message({
            message: 'token失效，2秒后跳转到登录页面！',
            type: 'error'
        });
          var timeout = setTimeout(function () {
              window.parent.location.href=baseURL+"login.html";
              clearTimeout(timeout);
        },2000)
    }
})

/********************* 通用方法start *********************/
//定义全局变量验证手机号
const checkPhone = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('手机号不能为空'));
    } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
            callback();
        } else {
            return callback(new Error('请输入正确的手机号'));
        }
    }
};

function setAddress(datas) {
    var address = [];
    $.each(datas, function (k, province) {
        // console.log(province);
        //省
        if (province && province.provinceCodeId) {
            var pro = {}
            pro['value'] = province.provinceCodeId
            pro['label'] = province.provinceName
            if (province.citys && province.citys.length > 0) {
                //市
                pro['children'] = []
                $.each(province.citys, function (k1, city) {
                    if (city.cityCodeId) {
                        var c = {}
                        c['value'] = city.cityCodeId
                        c['label'] = city.cityName
                        //区
                        var regions = []
                        if (city.regions && city.regions.length > 0) {
                            $.each(city.regions, function (k2, region) {
                                if (region.regionCodeId) {
                                    var reg = {}
                                    reg['value'] = region.regionCodeId
                                    reg['label'] = region.regionName
                                    regions.push(reg)
                                }
                            });
                        }
                        c['children'] = regions
                        pro['children'].push(c)
                    }
                })
            }
            address.push(pro)
        }
    })
    return address;
}

//获取省市县方法
Vue.prototype.getAddress = function () {
    var url = baseURL + 'resource/getResourse';
    axios.get(url)
        .then(function (res) {
            vm.address = setAddress(res.data.data);
        })
        .catch(function (error) {
            console.log(error);
        });
}
/********** 上传start **********/
Vue.prototype.doUpload = function () {
}
Vue.prototype.beforeUpload = function (file) {
    var fd = new FormData();
    fd.append('file', file);//传文件
    fd.append('folder', vm.folder);//传其他参数
    // axios.post(baseURL + 'business/upload?token=' + token, fd).then(
    axios.post(baseURL + 'api/upload', fd).then(
        function (res) {
            if (res.data.code == 0) {
                vm.setPic(res.data.path)
                vm.$message({
                    message: '上传成功',
                    type: 'success'
                });
            } else {
                vm.$message({
                    message: res.data.msg,
                    type: 'error'
                });
            }

        }).catch(function (error) {
        console.log(error);
        vm.$message({
            message: '上传失败',
            type: 'error'
        });
    });
}
Vue.prototype.handleRemove = function (file, fileList) {
    //索引位置
    var index = ''
    $.each(vm.fileList, function (k, v) {
        if (v.uid == file.uid) {
            index = k;
        }
    })
    //删除
    console.log(fileList);
    vm.addForm.picList.splice(index, 1)

    this.fileList = fileList
}
/********** 上传end **********/
//格式化日期
Vue.prototype.Format = function (datetime, fmt) {
    if (parseInt(datetime) == datetime) {
        if (datetime.length == 10) {
            datetime = parseInt(datetime) * 1000;
        } else if (datetime.length == 13) {
            datetime = parseInt(datetime);
        }
    }
    datetime = new Date(datetime);
    var o = {
        "M+": datetime.getMonth() + 1,                 //月份
        "d+": datetime.getDate(),                    //日
        "h+": datetime.getHours(),                   //小时
        "m+": datetime.getMinutes(),                 //分
        "s+": datetime.getSeconds(),                 //秒
        "q+": Math.floor((datetime.getMonth() + 3) / 3), //季度
        "S": datetime.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1,
            (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1,
                (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(
                    ("" + o[k]).length)));
        }
    }
    return fmt;
}
/********** 富文本start **********/
Vue.use(window.VueQuillEditor);
//父组件获取子组件传来的值
Vue.prototype.getValues = function (cont) {
    Vue.set(vm.addForm, vm.fieldname, cont)
}
//设置富文本信息
Vue.prototype.setValues = function (val) {
    $('.ql-editor').html('')
    $('.ql-editor').append(val)
}
/********** 富文本end **********/

/********** 全局配置Axios请求start **********/
// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数
function startLoading() {
    loading = Vue.prototype.$loading({
        lock: true,
        text: '努力加载中...',
        background: 'rgba(0,0,0,0.5)',
        target: document.querySelector('.loading-area') // 设置加载动画区域
    })
}

function endLoading() {
    loading.close()
}

function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

function hideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

axios.defaults.headers.post['token'] = token;
axios.defaults.headers.get['token'] = token;

Vue.config.productionTip = false
// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    if (config.isLoading !== false) { // 如果配置了isLoading: false，则不显示loading
        showFullScreenLoading()
    }
    return config;
}, function (error) {
    // Do something with request error
    hideFullScreenLoading()
    return Promise.reject(error.response)
    // return Promise.reject(error);
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    hideFullScreenLoading() // 响应成功关闭loading
    return response;
}, function (error) {
    hideFullScreenLoading()
    // Do something with response error
    return Promise.reject(error);
});
/********** 全局配置Axios请求end **********/

/********** 封装Axios请求start **********/
Vue.prototype.api = {
    async get(url, data) {
        try {
            let res = await axios.get(url, {params: data})
            res = res.data
            return new Promise((resolve) => {
                if (res.code === 0) {
                    resolve(res)
                } else {
                    resolve(res)
                }
            })
        } catch (err) {
            alert('服务器出错')
            console.log(err)
        }
    },
    async post(url, data) {
        try {
            let res;
            // if(Object.prototype.toString.call(data)=="[object Array]"){
            res = await axios.post(url, Qs.stringify(data, {arrayFormat: 'repeat'}))
            // }else {
            //   res = await axios.post(url, Qs.stringify(data))
            // }
            res = res.data
            return new Promise((resolve, reject) => {
                if (res.code === 0) {
                    resolve(res)
                } else {
                    reject(res)
                }
            })
        } catch (err) {
            // return (e.message)
            alert('服务器出错')
            console.log(err)
        }
    }
}
/********** 封装Axios请求end **********/

/********************* 通用方法end *********************/

/********************* business方法start *********************/
//查询
Vue.prototype.query = function () {
    vm.currentPage = 1
    vm.getEntityList()
}
//刷新
Vue.prototype.reload = function () {
    location.href = location.href
}
//导出
Vue.prototype.exportExcel = function () {
    var url = baseURL + vm.excelExportUrl + '?token=' + token;
    $.each(vm.q, function (k, v) {
        url += '&' + k + '=' + v
    });
    window.top.location.href = url;
}
//alert提示框
Vue.prototype.vAlert = function (msg, title) {
    vm.$alert(msg, title, {
        confirmButtonText: '确定'
    });
}
//授权
Vue.prototype.hasPermission = function (permission) {//hasPermission是函数名
    return hasPermission(permission)
}
//获取列表
Vue.prototype.getEntityList = function () {
    var data = {page: this.currentPage, limit: this.pageSize, ...this.q}
    // axios.post(baseURL + this.listUrl + '?token=' + token, data)
    axios.post(baseURL + this.listUrl, data)
        .then((res) => {
            this.entityList = res.data.page.records;
            this.total = res.data.page.total;
        })
        .catch(function (error) {
            console.log(error);
        });
}
// 初始页currentpage、初始每页数据数pagesize和数据data
Vue.prototype.handleSizeChange = function (size) {
    vm.pageSize = size;
    console.log(this.pageSize)  //每页下拉显示数据
    vm.getEntityList()
};
Vue.prototype.handleCurrentChange = function (currentPage) {
    vm.currentPage = currentPage;
    vm.getEntityList()
}
//删除
Vue.prototype.del = function (ids) {
    if (ids.length == 0) {
        return false;
    }
    this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        axios.post(baseURL + vm.delUrl, ids)
            .then((res) => {
                if (res.data.msg == 'token失效，请重新登录') {
                    alert('token失效，2秒后跳转到登录页面！');
                    var timeout = setTimeout(function () {
                        window.parent.location.href = baseURL + "login.html";
                        clearTimeout(timeout);
                    }, 2000)
                } else if (res.data.code == 0) {
                    vm.$message({
                        type: 'success',
                        message: '删除成功'
                    });
                    vm.getEntityList();
                } else {
                    alert(res.data.msg);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }).catch(() => {
        vm.$message({
            type: 'info',
            message: '已取消删除'
        });
    });
}
//更新状态
Vue.prototype.updateStatus = function (data, msg) {
    axios.post(baseURL + vm.updateStatusUrl, data)
        .then(function (res) {
            if (res.data.code === 0) {
                vm.$message({
                    message: res.data.msg,
                    type: 'success'
                });
                vm.getEntityList();
            } else {
                alert(res.data.msg);
            }
        })
        .catch(function (error) {
            console.log(error);
        });
}
//多选
Vue.prototype.changeFun = function (val) {
    vm.changeArr = val;
}
//部门下拉列表
Vue.prototype.getRoleList = function () {
    $.get(baseURL + "sys/role/select", function (r) {
        vm.roleList = r.list;
    });
}
//获取图片路径
Vue.prototype.getPic = function (path) {
    return imageURL + path;
}
//数组去重方法
Vue.prototype.unique = function (arr, idName) { // 根据唯一标识orderId来对数组进行过滤
    const res = new Map();  //定义常量 res,值为一个Map对象实例
    //返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
    return arr.filter((arr) => !res.has(arr[idName]) && res.set(arr[idName], 1))
}


/********************* business方法end *********************/